/*
 * stateMachine.c
 *
 * Created: 6/29/2013 5:05:16 PM
 *  Author: Tim
 */ 

#include "stateMachine.h"
#include "allocations.h"

#include "../packets/structs/msgHeaderDefs.h"
#include "../packets/structs/genPacketStructs.h"
#include "../packets/handlers/adcPacketHandler.h"
#include "../packets/handlers/genPacketHandler.h"

#include "../extFlash/flash.h"


void startProgram()
{	
	if(daqAlloc.standAlone.aqState == AQ_AQUIRE_STATE) 
	{
		asm("nop");
		return;
	}
	
	//start adc channels that have been allocated
	if (daqAlloc.analogAlloc.analogInCh0Alloc)	
	{	
		ADCA.CH0.INTCTRL = ADC_CH_INTLVL_LO_gc;
	}
	if (daqAlloc.analogAlloc.analogInCh1Alloc)	
	{
		ADCA.CH1.INTCTRL = ADC_CH_INTLVL_LO_gc;
	}
	if (daqAlloc.analogAlloc.analogInCh2Alloc)	
	{
		ADCA.CH2.INTCTRL = ADC_CH_INTLVL_LO_gc;
	}
	if (daqAlloc.analogAlloc.analogInCh3Alloc)	
	{
		ADCA.CH3.INTCTRL = ADC_CH_INTLVL_LO_gc;
	}
	
	if(daqAlloc.standAlone.daqStandAlone) 
	{
		daqAlloc.standAlone.aqState = AQ_AQUIRE_STATE;	//data aquisition will begin now since timer interrupts are now enabled 
		chipErase();
		while(readStatusReg() & STSRG_BUSY_msk);
	}
	
	//turn on timer interrupts if the timers are allocated
	if (daqAlloc.timerAlloc.timerC0Alloc && daqAlloc.encAlloc.enc0TmrAlloc != TIMER_C0 && daqAlloc.encAlloc.enc1TmrAlloc != TIMER_C0) TCC0.INTCTRLA = TC_OVFINTLVL_LO_gc;
	if (daqAlloc.timerAlloc.timerC1Alloc && daqAlloc.encAlloc.enc0TmrAlloc != TIMER_C1 && daqAlloc.encAlloc.enc1TmrAlloc != TIMER_C1) TCC1.INTCTRLA = TC_OVFINTLVL_LO_gc;
	if (daqAlloc.timerAlloc.timerD0Alloc && daqAlloc.encAlloc.enc0TmrAlloc != TIMER_D0 && daqAlloc.encAlloc.enc1TmrAlloc != TIMER_D0) TCD0.INTCTRLA = TC_OVFINTLVL_LO_gc;
	if (daqAlloc.timerAlloc.timerD1Alloc && daqAlloc.encAlloc.enc0TmrAlloc != TIMER_D1 && daqAlloc.encAlloc.enc1TmrAlloc != TIMER_D1) TCD1.INTCTRLA = TC_OVFINTLVL_LO_gc;
	if (daqAlloc.timerAlloc.timerE0Alloc && daqAlloc.encAlloc.enc0TmrAlloc != TIMER_E0 && daqAlloc.encAlloc.enc1TmrAlloc != TIMER_E0) TCE0.INTCTRLA = TC_OVFINTLVL_LO_gc;

}

void stopProgram()
{	
	//disable com data
	USARTD1.CTRLA &= ~USART_DREINTLVL_gm;
	
	//disable all timer interrupts
	TCC0.INTCTRLA = TC_OVFINTLVL_OFF_gc;
	TCC1.INTCTRLA = TC_OVFINTLVL_OFF_gc;
	TCD0.INTCTRLA = TC_OVFINTLVL_OFF_gc;
	TCD1.INTCTRLA = TC_OVFINTLVL_OFF_gc;
	TCE0.INTCTRLA = TC_OVFINTLVL_OFF_gc;
	
	//stop all the adc channel interrupts
	ADCA.CH0.INTCTRL = ADC_CH_INTLVL_OFF_gc;
	ADCA.CH1.INTCTRL = ADC_CH_INTLVL_OFF_gc;
	ADCA.CH2.INTCTRL = ADC_CH_INTLVL_OFF_gc;
	ADCA.CH3.INTCTRL = ADC_CH_INTLVL_OFF_gc;
}

void standAloneEnable()
{
	daqAlloc.standAlone.daqStandAlone = FEATURE_UTILIZED;
	daqAlloc.standAlone.aqState = AQ_INIT_STATE;
	chipErase();
}
